package com.yirui.bridge.controller;

import com.yirui.bridge.annotation.SourceType;
import com.yirui.bridge.core.Server;
import com.yirui.bridge.core.ServerManager;
import com.yirui.bridge.core.SourceTypeContext;
import com.yirui.bridge.tcp.NettyTcpClient;
import com.yirui.bridge.tcp.server.AgentServer;
import io.netty.buffer.Unpooled;
import io.netty.util.CharsetUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

/**
 * @author Dujie
 * @create 2021/11/3
 * @since 1.0.0
 */
@RestController
@RequestMapping("/tcpServer")
@SourceType("tcpServer")
public class TcpServerController {

    @Autowired
    private ServerManager serverManager;
    /**
     * 获取设备状态
     * @return
     */
    @RequestMapping("/status")
    public Server getStatus() throws Exception {
        return serverManager.getServer();
    }

    /**
     * 发送操作指令
     * @return
     */
    @RequestMapping("/send")
    public Map send(@RequestParam(value="value") String value, @RequestHeader(value = "targetHost") String targetHost){
        Map res = new HashMap();
        try {
            AgentServer agentServer = (AgentServer) serverManager.getServer();
            if(agentServer == null||agentServer.getChannel() == null){
                res.put("success", false);
                res.put("error", "目标服务未正常连接上");
                res.put("status","服务对象是空的");
            }else {
                boolean success = agentServer.send(targetHost, value);
                res.put("success", success);
                res.put("lastSentValue", value);
                res.put("error", success?"":"客户端:"+targetHost+"不存在");
            }
        }catch (Exception ex){
            res.put("success", false);
            res.put("error", ex.toString());
        }
        return res;
    }
}
